package com.yima.baseproj.security.annotation;

import com.yima.baseproj.utils.AppContextUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 *
 * @Author 一码
 * @createDate 2023/4/1 09:00
 * @contact 1424529270@qq.com
 */
public class SecurityIgnoreUrlUtil {

    /**
     * 是否忽略URL
     * @param request
     * @return
     */
    public static Boolean isIgnoredUrl(HttpServletRequest request){
        Boolean isIgnoredUrl = false;
        try {
            // 白名单URL【注解】
            //通过ApplicationContext上下文（spring）找到RequestMappingHandlerMapping这个bean
            RequestMappingHandlerMapping handlerMapping = AppContextUtil.getBean(RequestMappingHandlerMapping.class);
            //RequestMappingHandlerMapping是对应url和处理类方法的一个类
            HandlerExecutionChain handlerChain = handlerMapping.getHandler(request);
            if(handlerChain != null){
                //通过处理链找到对应的HandlerMethod类
                HandlerMethod handler = (HandlerMethod) handlerChain.getHandler();
                //HandlerMethod中有bean和method
                Object bean = handler.getBean();//处理请求的类
                Method method = handler.getMethod();//处理请求的方法
                if(bean.getClass().isAnnotationPresent(SecurityIgnoreUrl.class)){
                    isIgnoredUrl = true;
                }
                if(method.isAnnotationPresent(SecurityIgnoreUrl.class)){
                    isIgnoredUrl = true;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return isIgnoredUrl;
    }

    /**
     * 是否包装
     * @param methodParameter
     * @return
     */
    public static Boolean isNeedResultVo(MethodParameter methodParameter){
        Boolean isIgnoredUrl = true;

        Method method = methodParameter.getMethod();//处理请求的方法
        Class mClass = methodParameter.getContainingClass();

        if(mClass.isAnnotationPresent(SecurityIgnoreUrl.class)){
            SecurityIgnoreUrl securityIgnoreUrl = (SecurityIgnoreUrl) mClass.getDeclaredAnnotation(SecurityIgnoreUrl.class);
            if(!securityIgnoreUrl.isNeedResultVo()){
                isIgnoredUrl = false;
            }
        }
        if(method.isAnnotationPresent(SecurityIgnoreUrl.class)){
            SecurityIgnoreUrl securityIgnoreUrl = (SecurityIgnoreUrl) method.getDeclaredAnnotation(SecurityIgnoreUrl.class);
            if(!securityIgnoreUrl.isNeedResultVo()){
                isIgnoredUrl = false;
            }
        }

        return isIgnoredUrl;
    }
}
